package com.daka.controller;

import com.alibaba.fastjson.JSONObject;
import com.daka.entity.*;
import com.daka.enumerate.StatusCode;
import com.daka.service.*;
import com.daka.tools.AesUtil;
import com.daka.tools.DateUtil;
import com.daka.vo.request.CreateOrderVo;
import com.daka.vo.response.BaseResponseVo;
import com.daka.vo.response.CheckUserVo;
import com.daka.vo.response.DataResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author beliveli on 2016/4/7.
 *         用户
 */
@Controller
@RequestMapping(value = "/spreadInsurance")
@Slf4j
public class SpreadInsuranceController {

    final String PINGAN_AES_KEY = "29aec3c3f0866c11ac75296766574b1f";

    @Resource
    private MemberService memberService;

    @Resource
    private SpreadInsuranceService spreadInsuranceService;

    @Resource
    private MemberInsuranceService memberInsuranceService;

    @Resource
    private PinganBankOpenRecordService pinganBankOpenRecordService;

    @Resource
    private MemberOrgService memberOrgService;

    @Resource
    private MemberInviteService memberInviteService;

    @ResponseBody
    @RequestMapping(value = "/saveInviteCode", method = RequestMethod.POST)
    public DataResponseVo<SpreadInsurance> saveInviteCode(@RequestBody CreateOrderVo createOrderVo) {
        log.info("/spreadInsurance/saveInviteCode param  ======> " + createOrderVo);
        Member member = memberService.selectByMemberId(createOrderVo.getMemberId());

        //保存邀请码\memberID
        MemberInvite memberInvite = new MemberInvite();
        memberInvite.setMemberId(member.getMemberID());
        memberInvite.setInviteCode(createOrderVo.getInviteCode());
        memberInviteService.insert(memberInvite);

        return new DataResponseVo<SpreadInsurance>(StatusCode.OK.getCode(), StatusCode.OK.getMessage());
    }

    @ResponseBody
    @RequestMapping(value = "/findInviteCode", method = RequestMethod.POST)
    public DataResponseVo<SpreadInsurance> findInviteCode(@RequestBody CreateOrderVo createOrderVo) {

        log.info("/spreadInsurance/findInviteCode param  ======> " + createOrderVo);

        //保存邀请码\memberID
        MemberInvite memberInvite = memberInviteService.selectByInviteCode(createOrderVo.getInviteCode());

        if (null == memberInvite){
            return new DataResponseVo<SpreadInsurance>(StatusCode.SERVER_EXCEPTION.getCode(), "邀请码不存在！");
        }else {
            return new DataResponseVo<SpreadInsurance>(StatusCode.OK.getCode(), StatusCode.OK.getMessage());
        }

    }

    @ResponseBody
    @RequestMapping(value = "/createOrder", method = RequestMethod.POST)
    public DataResponseVo<SpreadInsurance> createOrder(@RequestBody CreateOrderVo createOrderVo) {

        log.info("/spreadInsurance/createOrder param  ======> " + createOrderVo);

        if(StringUtils.isEmpty(createOrderVo.getMemberId())){
            return new DataResponseVo<SpreadInsurance>(StatusCode.USER_NOT_EXISTS.getCode(), StatusCode.COMMON_USER_NOT_LOGIN.getMessage());
        }
        Member member = memberService.selectByMemberId(createOrderVo.getMemberId());

        if (createOrderVo.getInviteCode() == null) {
            return new DataResponseVo<SpreadInsurance>(StatusCode.COMMON_PARAM_ERROR.getCode(), StatusCode.COMMON_PARAM_ERROR.getMessage());
        }

        SpreadInsurance spreadInsurance = new SpreadInsurance();
        spreadInsurance.setStatus(20);
        spreadInsurance.setName(member.getRealName());
        spreadInsurance.setMobile(member.getBundMobile());
        spreadInsurance.setBusinessCode(createOrderVo.getBusinessCode());
        spreadInsurance.setChannelCode(createOrderVo.getChannelCode());
        spreadInsurance.setCardNo(member.getCardNO());
        spreadInsurance.setSpreadCode(createOrderVo.getInviteCode());
        spreadInsurance.setVolunteerCode(member.getVolunteerCode());

        spreadInsurance = spreadInsuranceService.create(spreadInsurance);

        return new DataResponseVo<SpreadInsurance>(StatusCode.OK.getCode(), StatusCode.OK.getMessage(), spreadInsurance);
    }

    @ResponseBody
    @RequestMapping(value = "/checkUser", method = RequestMethod.POST)
    public DataResponseVo<CheckUserVo> checkUser(@RequestBody CreateOrderVo createOrderVo) {
        log.info("/spreadInsurance/checkUser param  ======> " + createOrderVo);

        if(StringUtils.isEmpty(createOrderVo.getMemberId())){
            return new DataResponseVo<CheckUserVo>(StatusCode.USER_NOT_EXISTS.getCode(), StatusCode.COMMON_USER_NOT_LOGIN.getMessage());
        }
        Member member = memberService.selectByMemberId(createOrderVo.getMemberId());
        if(null == member){
            return new DataResponseVo<CheckUserVo>(StatusCode.USER_NOT_EXISTS.getCode(), StatusCode.COMMON_USER_NOT_LOGIN.getMessage());
        }

        List<MemberOrg> memberOrg = memberOrgService.checkLader(member.getId());
        //查询code
        List<MemberInvite> list = memberInviteService.selectByMember(member.getMemberID());
        String inviteCode = "";
        if (list.size() > 0) {
            inviteCode = list.get(0).getInviteCode();
        }

        Boolean havingInsurance = false;
        if(StringUtils.isNotEmpty(member.getVolunteerCode())){
            MemberInsurance memberInsurance = memberInsuranceService.findByVolunteerCode(member.getVolunteerCode());
            if(null != memberInsurance){
                havingInsurance = true;
            }
        }

        if (memberOrg.size() > 0) {
            return new DataResponseVo<CheckUserVo>(StatusCode.OK.getCode(), StatusCode.OK.getMessage(), CheckUserVo.build(member, Boolean.TRUE, inviteCode,havingInsurance));
        }
        return new DataResponseVo<CheckUserVo>(StatusCode.OK.getCode(), StatusCode.OK.getMessage(), CheckUserVo.build(member, Boolean.FALSE, inviteCode,havingInsurance));
    }

    @ResponseBody
    @RequestMapping(value = "/callBack", method = RequestMethod.POST)
    public BaseResponseVo callBack(@RequestParam("resultJson") String resultJson) {

        log.info("/spreadInsurance/checkUser param  ======> " + resultJson);

        String resultStr = "";
        try {
            resultStr = AesUtil.decrypt(resultJson, PINGAN_AES_KEY);
        } catch (Exception e) {
            log.error("返回值解密失败 ！");
            e.printStackTrace();
        }

        log.info("/spreadInsurance/checkUser param  解密后 ======> " + resultStr);

        if (StringUtils.isNotEmpty(resultStr)) {
            JSONObject resultObject = JSONObject.parseObject(resultStr);

            if (resultObject.getBoolean("success")) {

                JSONObject insuranceJson = resultObject.getJSONObject("obj").getJSONObject("insurance");

                JSONObject bankAccount = resultObject.getJSONObject("obj").getJSONObject("bankAccount");
                String spreadInsuranceId = resultObject.getJSONObject("obj").getString("orderCode");

                if (null != insuranceJson && StringUtils.isNotEmpty(insuranceJson.getString("volunteerCode"))){
                    //保存志愿者保险信息
                    MemberInsurance volunteerInsurance = memberInsuranceService.findByVolunteerCode(insuranceJson.getString("volunteerCode"));
                    if (null == volunteerInsurance) {
                        volunteerInsurance = new MemberInsurance();
                        volunteerInsurance.setCreatetime(DateUtil.date2Str(insuranceJson.getDate("createTime"), DateUtil.DATETIME_YYYY_MM_DD_HH_MM_SS));
                        volunteerInsurance.setInsuranceno(insuranceJson.getString("insuranceNo"));
                        volunteerInsurance.setVolunteercode(insuranceJson.getString("volunteerCode"));
                        volunteerInsurance.setPeriodEnd(insuranceJson.getString("periodEnd"));
                        volunteerInsurance.setPeriodStart(insuranceJson.getString("periodStart"));
                        volunteerInsurance.setServiceProvider("上海悠活网络科技有限公司");
                        volunteerInsurance.setStatus(1);

                        volunteerInsurance = memberInsuranceService.save(volunteerInsurance);
                    }

                    //保存平安开户信息
                    PinganBankOpenRecord pinganOpen = pinganBankOpenRecordService.findByVolunteerCode(insuranceJson.getString("volunteerCode"));
                    if (null == pinganOpen) {
                        pinganOpen = new PinganBankOpenRecord();
                        pinganOpen.setVolunteercode(insuranceJson.getString("volunteerCode"));
                        pinganOpen.setIdcard(bankAccount.getString("idNo"));
                        pinganOpen.setMobile(bankAccount.getString("mobile"));
                        pinganOpen.setName(bankAccount.getString("realName"));
                        pinganOpen.setStatus(bankAccount.getInteger("isNewCus"));
                        pinganOpen.setCardnum(bankAccount.getString("bankAcnt"));
                        pinganOpen.setSn("A" + new Date().getTime());

                        pinganOpen = pinganBankOpenRecordService.save(pinganOpen);
                    }

                    //更新推广结果
                    SpreadInsurance spreadInsurance = spreadInsuranceService.findById(Long.valueOf(spreadInsuranceId));

                    spreadInsurance.setVolunteerCode(volunteerInsurance.getVolunteercode());
                    spreadInsurance.setPinganCardNo(bankAccount.getString("bankAcnt"));
                    spreadInsurance.setInsuranceCode(insuranceJson.getString("insuranceNo"));
                    spreadInsurance.setStatus(10);

                    spreadInsuranceService.updateById(spreadInsurance);

                    //更新志愿者编码
                    Member member = memberService.selectByCardNo(pinganOpen.getIdcard());
                    if(null != member){
                        member.setVolunteerCode(volunteerInsurance.getVolunteercode());
                        memberService.update(member);
                    }

                }else{
                    //更新推广结果
                    SpreadInsurance spreadInsurance = spreadInsuranceService.findById(Long.valueOf(spreadInsuranceId));
                    spreadInsurance.setPinganCardNo(bankAccount.getString("bankAcnt"));
                    spreadInsurance.setStatus(10);

                    spreadInsuranceService.updateById(spreadInsurance);
                }
            }
        }
        return new BaseResponseVo(StatusCode.OK.getCode(), StatusCode.OK.getMessage());
    }
}